﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace WITD
{
    /// <summary>
    /// A Window class for add a new Team Foundation Server categoryName.
    /// </summary>
    public partial class AddCategory : Window
    {
        Project CurrentProject;
        String DefaultWITName;
        bool _created = false;

        /// <summary>
        /// Denotes the success of attempting to create a new categoryName.
        /// </summary>
        public bool Success
        {
            get
            {
                return _created;
            }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="project">The team project to work with.</param>
        /// <param name="parent">The owning Window object instance. It must have been shown at least once to avoid an Exception.</param>
        public AddCategory(Project project, Window parent)
        {
            InitializeComponent();
            CurrentProject = project;
            Owner = parent;
            PopulateWITDs(project);
            txtFriendlyName.Focus();
        }

        /// <summary>
        /// Calls the method <see cref="CreateCategory">CreateCategory()</see> to create a new categoryName with the values entered 
        /// by the user.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
                        
            if (!String.IsNullOrEmpty(txtReferenceName.Text) && txtReferenceName.Text.Contains("."))
            {
                if (!String.IsNullOrEmpty(txtFriendlyName.Text))
                {
                    if (!String.IsNullOrEmpty(DefaultWITName))
                    {
                        _created = CreateCategory(txtReferenceName.Text, txtFriendlyName.Text, DefaultWITName);
                    }
                    else
                    {
                        MessageBox.Show("Error: Please select a work item type to be the default for the new category.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Error: Please enter an appropriate friendly name for the new category.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                MessageBox.Show("Error: Please enter an appropriate reference name for the new category.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// Displays an error message if specified
        /// </summary>
        /// <param name="message">Optionally has an error message.</param>
        /// <param name="caller">The calling method name.</param>
        private static void ShowError(String message, String caller)
        {
            if (!String.IsNullOrEmpty(message))
            {
                MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                MessageBox.Show("Error in " + caller + ".", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// Creates a new categoryName with the specified reference name, friendly name, and default work item type name.
        /// </summary>
        /// <param name="referenceName">The reference name of the categoryName to create.</param>
        /// <param name="friendlyName">The friendly or display name of the categoryName.</param>
        /// <param name="defaultWIT">The default <see cref="WorkItemType">WorkItemType</see> for the new categoryName. This must already be in the team project.</param>
        /// <returns>True if successful. Otherwise false.</returns>
        private bool CreateCategory(String referenceName, String friendlyName, String defaultWIT)
        {
            bool success = false;
            String message = "";

            try
            {
                SetCursor(Cursors.Wait);
                WorkItemCategory catMgr = new WorkItemCategory(CurrentProject);
                success = catMgr.CreateCategory(referenceName, friendlyName, defaultWIT, out message);

                if (!success)
                {
                    ShowError(message, System.Reflection.MethodInfo.GetCurrentMethod().Name);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                SetCursor(Cursors.Arrow);
            }

            return success;
        }

        /// <summary>
        /// Cancels adding a new categoryName and closes this window.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        /// <summary>
        /// Fills the work item type list box for the specified project.
        /// </summary>
        /// <param name="project">The team project to list work item types for.</param>
        private void PopulateWITDs(Project project)
        {
            foreach (WorkItemType wit in project.WorkItemTypes)
            {
                cboWITs.Items.Add(wit.Name);
            }
            cboWITs.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription());
        }

        /// <summary>
        /// Stores the new selected work item type.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboWITs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cboWITs.SelectedItem != null)
            {
                DefaultWITName = cboWITs.SelectedItem as String;
            }
        }

        /// <summary>
        /// Sets the mouse cursor to the specified cursor.
        /// </summary>
        /// <param name="newCursor">The new cursor.</param>
        public void SetCursor(Cursor newCursor)
        {
            this.Cursor = newCursor;
        }
    }
}
